package aqv



import static org.springframework.http.HttpStatus.*
import commands.LoginCommand
import grails.transaction.Transactional


class UserController {

    //static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
	
	static scaffold = User
	

	
	def list(){
		redirect (action:'index')
	}
	
	
	def index(){
		render(view: "login")
	}
	
	

	def login(LoginCommand cmd) {
		
		if(request.method == 'POST') {
			if(!cmd.hasErrors()) {
				session.user = cmd.getUser()
				redirect controller:'politician'
			} else {
				render (view:'/User/login', model:[loginCmd:cmd])
			}
		}
	}
	
	
	def logout() {
		session.user = null
		redirect (controller:'application')
	}
	
	
	
	def register(){
		
		if(request.method == 'POST') {
			def u = new User()
			u.properties['username', 'password', 'firstName', 'lastName', 'email', 'politicalParty', 'politicalPartyRole'] = params
			u.properties['apiKey'] = (params.login+params.email).hashCode()
			u.properties['confirm'] = false
			u.properties['accountExpired'] = false
			u.properties['accountLocked'] = false
			u.properties['passwordExpired'] = false
			u.properties['enabled'] = true
			
			
			if(u.password != params.confirm) {
				
				u.errors.rejectValue("password", "error.user.password.dontmatch")
				render(view: "register", model: [userInstance: u])

			} else if(u.save()) {
			
				// send confirmation email
				try{
					println "BEGIN --- sending email"
					sendMail {
						to u.email
						subject 'Registration Confirmation'
						body view: '/emails/confirmRegistration',
						model: [user: u]
					}
					println "END    --- sending email"
				} catch (Exception e) {
					log.error("LOG -- an error ocurred : " + e.message)
					println "An error ocurred while sending email: \t " + e.stackTrace
				}
				
				
				// consider changing the redirect and save user session until user confirms registration
				
			
				//session.user = u
				redirect (controller:"politician")
				
			} else {
				render(view: "register", model: [userInstance: u])
			}
		}
		
	}
	
	
	
	def validateUser(){
		
		User user = User.findByUsername(params.username)
		
		if (!user.confirm) {
			
			if (user.apiKey == params.apiKey) {

				user.confirm = true
				user.save();

				// here the counter of people in the political party should increase
				def politicalParty = PoliticalParty.get(user.politicalParty.id)
				politicalParty.cantOfPoliticians += 1
				
				
				
				
				// creation of roles 
				Role role = Role.findByAuthority('ROLE_USER')
				if (politicalParty.cantOfPoliticians == 1) {
					role = Role.findByAuthority('ROLE_ADMIN')
					politicalParty.admin = user
				}
				
				
				
				
				
				UserRole.create(user, role, true)
				
				
				politicalParty.save()

				
				// redirect to auth of login controller
				redirect (controller: "login")
			} else {
				// validation problem, security breach
				flash.message = message(code: 'error.permission.isRealyTheUser', args: [user.lastName, user.firstName])
				redirect (controller: "login")
				//render (view: "login")
			}
		} else {
			flash.message = message(code: 'error.permission.userAlreadyConfirmed', args: [user.lastName, user.firstName])
			redirect (controller: "login")
			//render (view: "login")
		}
		
	}
	
	
	
//
//    def index(Integer max) {
//        params.max = Math.min(max ?: 10, 100)
//        respond User.list(params), model:[userInstanceCount: User.count()]
//    }
//
//    def show(User userInstance) {
//        respond userInstance
//    }
//
//    def create() {
//        respond new User(params)
//    }
//
//    @Transactional
//    def save(User userInstance) {
//        if (userInstance == null) {
//            notFound()
//            return
//        }
//
//        if (userInstance.hasErrors()) {
//            respond userInstance.errors, view:'create'
//            return
//        }
//
//        userInstance.save flush:true
//
//        request.withFormat {
//            form multipartForm {
//                flash.message = message(code: 'default.created.message', args: [message(code: 'userInstance.label', default: 'User'), userInstance.id])
//                redirect userInstance
//            }
//            '*' { respond userInstance, [status: CREATED] }
//        }
//    }
//
//    def edit(User userInstance) {
//        respond userInstance
//    }
//
//    @Transactional
//    def update(User userInstance) {
//        if (userInstance == null) {
//            notFound()
//            return
//        }
//
//        if (userInstance.hasErrors()) {
//            respond userInstance.errors, view:'edit'
//            return
//        }
//
//        userInstance.save flush:true
//
//        request.withFormat {
//            form multipartForm {
//                flash.message = message(code: 'default.updated.message', args: [message(code: 'User.label', default: 'User'), userInstance.id])
//                redirect userInstance
//            }
//            '*'{ respond userInstance, [status: OK] }
//        }
//    }
//
//    @Transactional
//    def delete(User userInstance) {
//
//        if (userInstance == null) {
//            notFound()
//            return
//        }
//
//        userInstance.delete flush:true
//
//        request.withFormat {
//            form multipartForm {
//                flash.message = message(code: 'default.deleted.message', args: [message(code: 'User.label', default: 'User'), userInstance.id])
//                redirect action:"index", method:"GET"
//            }
//            '*'{ render status: NO_CONTENT }
//        }
//    }
//
//    protected void notFound() {
//        request.withFormat {
//            form multipartForm {
//                flash.message = message(code: 'default.not.found.message', args: [message(code: 'userInstance.label', default: 'User'), params.id])
//                redirect action: "index", method: "GET"
//            }
//            '*'{ render status: NOT_FOUND }
//        }
//    }
}
